package com.xizi.proxy_cglib;

import com.xizi.proxy_jdk.JDKAnimal;
import org.junit.Test;
import sun.misc.ProxyGenerator;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @author: LiYanChao
 * @create: 2018-11-02 14:11
 */
public class GenJdkProxyClass {

    /**
     * 生成代理类的名称
     */
    private static String DEFAULT_CLASS_NAME = "$Proxy";

    /**
     * 默认生成的文件全路径
     */
    private static String DEFAULT_FILE_PATH = "D:/IDEA/JavaWorkSpace/Spring-study/" + DEFAULT_CLASS_NAME + ".class";


    /**
     * 使用ProxyGenerator生成代理类.class文件
     *
     * @param path 文件路径
     */
    public static void genProxyClass(String path) {

        byte[] classFile = ProxyGenerator.generateProxyClass(DEFAULT_CLASS_NAME, new Class[]{CglibCat.class});
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(path);
            fos.write(classFile);
            fos.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Test
    public void TestGenProxyClass() {
        GenJdkProxyClass.genProxyClass(DEFAULT_FILE_PATH);
    }
}